package Blog

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/Blog"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"strconv"
)

type ShowBlogs struct {
	controllers.MainController
}

//过滤数据库构造响应数据
type BlogClearn struct {
	BlogID        int    //文章ID
	BlogTitle     string //文章标题
	BlogView      int    //文章阅读数量
	BlogUrl       string //文章路径
	EnableComment int    //是否允许评论
	CreateTime    string //文章创建时间
	IsDeleted     int    //是否删除
}

func (this *ShowBlogs) Get() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	userid, err1 := rd.Get(uuid)
	body := map[string]interface{}{"code": 200, "data": map[string]interface{}{}}
	if err1 != nil {
		body = map[string]interface{}{"code": 300, "msg": "异常请求"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//一对多关联查询
	db := models.ConnDb()
	defer db.Close()
	useridInt, err2 := strconv.Atoi(userid)
	if err2 != nil {
		body = map[string]interface{}{"code": 300, "msg": "服务器"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	u := User.TbUser{Uuid: useridInt}
	db.First(&u)
	var tb []Blog.TBloginfo
	var bc []BlogClearn
	db.Model(&u).Association("TBloginfo").Find(&tb)
	//渲染响应数据
	data, err3 := json.Marshal(tb)
	if err3 != nil {
		body = map[string]interface{}{"code": 300, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	err4 := json.Unmarshal(data, &bc)
	if err4 != nil {
		body = map[string]interface{}{"code": 300, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body = map[string]interface{}{"code": 200, "data": bc}
	this.Data["json"] = body
	this.ServeJSON()
}
